<?php

    namespace App\Http\Controllers\GA;

    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use Google_Client;
    use Illuminate\Support\Facades\Log;
    use Illuminate\Support\Facades\URL;

    class BaseController extends Controller
    {
        protected static $analytics;
        protected static $profile;
        protected static $results;
        public static    $config = __DIR__ . '/client_secrets.json';

        public function getFirstProfileId($analytics)
        {
            // Get the user's first view (profile) ID.

            // Get the list of accounts for the authorized user.
            $accounts = $analytics->management_accounts->listManagementAccounts();

            if (count($accounts->getItems()) > 0){
                $items          = $accounts->getItems();
                $firstAccountId = $items[0]->getId();

                // Get the list of properties for the authorized user.
                $properties = $analytics->management_webproperties
                    ->listManagementWebproperties($firstAccountId);

                if (count($properties->getItems()) > 0){
                    $items           = $properties->getItems();
                    $firstPropertyId = $items[0]->getId();

                    // Get the list of views (profiles) for the authorized user.
                    $profiles = $analytics->management_profiles
                        ->listManagementProfiles($firstAccountId, $firstPropertyId);

                    if (count($profiles->getItems()) > 0){
                        $items = $profiles->getItems();

                        // Return the first view (profile) ID.
                        return $items[0]->getId();

                    } else {
                        throw new Exception('No views (profiles) found for this user.');
                    }
                } else {
                    throw new Exception('No properties found for this user.');
                }
            } else {
                throw new Exception('No accounts found for this user.');
            }
        }

        public function getResults($analytics, $profileId)
        {
            // Calls the Core Reporting API and queries for the number of sessions
            // for the last seven days.
            return $analytics->data_ga->get(
                'ga:' . $profileId,
                '7daysAgo',
                'today',
                'ga:sessions');
        }

        /**
         * GA
         * @param Request $request
         *
         * @throws \Google_Exception
         * test
         * author: walker
         * Date: 2019/11/18
         * Time: 18:03
         * Note:
         */
        public function test(Request $request)
        {
            $client = new Google_Client();


            $client->setAuthConfig(self::$config);
            $client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);
            $accessToken = session('access_token');
            if (isset($accessToken) && $accessToken){
                $client->setAccessToken($accessToken);
                $analytics = new \Google_Service_Analytics($client);
                $profile   = $this->getFirstProfileId($analytics);
                $res       = $this->getResults($analytics, $profile);
                echo "<pre>";
                print_r($res);
                die();
            } else {
                $url          = action('\App\Http\Controllers\GA\BaseController@callBack');
                $redirect_uri = $url;
                header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
            }


        }

        /**
         * GA授权回调函数
         * @throws \Google_Exception
         * callBack
         * author: walker
         * Date: 2019/11/18
         * Time: 18:03
         * Note:
         */
        public function callBack()
        {
            $client = new Google_Client();
            $client->setAuthConfig(self::$config);
            $url          = action('\App\Http\Controllers\GA\BaseController@callBack');
            $redirect_uri = $url;
            $client->setRedirectUri($redirect_uri);
            $client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);
            if ( !isset($_GET['code'])){
                $authUrl = $client->createAuthUrl();
                header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
            } else {
                $client->authenticate($_GET['code']);
                $accessToken= $client->getAccessToken();
                session(['access_token'=>$accessToken]);
                $url          = action('\App\Http\Controllers\GA\BaseController@gaClient');

                $redirect_uri = $url;
                header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
            }
        }

        public function gaClient()
        {
            return view("ga");
        }

    }
